package com.ccys.common.third.push.firebase;



import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.messaging.*;
import lombok.extern.slf4j.Slf4j;

import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.ArrayList;
import java.util.List;


/**
 * 从官网获取的APP_KEY
 * <p>
 *
 * 参考文档：官方文档 https://firebase.google.com/docs/cloud-messaging/send-message?hl=zh-cn#java
 * https://firebase.google.com/docs/android/setup?hl=zh-cn
 * https://firebase.google.com/docs/cloud-messaging/http-server-ref?hl=zh-cn
 * https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages/send?hl=zh-cn
 *
 * https://wenku.baidu.com/view/5e20e4b052e79b89680203d8ce2f0066f533642e.html?_wkts_=1705029760632&bdQuery=firebase%E6%B6%88%E6%81%AF%E6%8E%A8%E9%80%81
 * 当前使用 https://www.jianshu.com/p/27bcfa43314f
 * https://juejin.cn/s/firebase%20push%E9%80%9A%E7%9F%A5%20java
 * Firebase Cloud Messaging （FCM） 跨平台消息传递解决方案，可以免费可靠的使用它传递消息
 * 已测试推送成功
 * @author Administrator
 */
@Slf4j
@Component
public class FireBaseUtil {

    public static final String FILE_PATH = "google/billy-s-bb32b-firebase-adminsdk-u6xc7-d1814b40a9.json";

    private static  FirebaseApp firebaseApp;

     //初始化SDK
     static {
         try {
             ClassPathResource resource = new ClassPathResource(FILE_PATH);
             InputStream   serviceAccount = resource.getInputStream();
             FirebaseOptions  options = null;
             try {
                 options = new FirebaseOptions.Builder()
                     .setCredentials(GoogleCredentials.fromStream(serviceAccount))
                     //.setCredentials(GoogleCredentials.fromStream(new ByteArrayInputStream(API_KEY.getBytes())))
                     //.setDatabaseUrl(dataUrl)
                     .build();
             } catch (IOException e) {
                 e.printStackTrace();
                 log.error("初始化SDK异常");
             }
             //初始化firebaseApp
             firebaseApp  = FirebaseApp.initializeApp(options);
             serviceAccount.close();
         } catch (Exception e) {
             e.printStackTrace();
         }
     }

    /**
     * 单设备推送 该方法已经测试通过
     * @param token        注册token
     * @param title        推送题目
     * @param body         推送内容
     * @return
     * @throws IOException
     * @throws FirebaseMessagingException
     */
    public static void pushSingle(String token, String title, String body) throws  FirebaseMessagingException {
        //构建消息内容  已经测试成功收到的代码
        /*Message message = Message.builder().setNotification(Notification.builder()
                .setTitle(title)
                .setBody(body)
            .build())
            .setToken(token)
            //订阅主题
            //.setTopic(topic)
            .build();*/
        Message message = Message.builder()
            .putData("title", title)
            .putData("body", body)
            .setToken(token)
            .build();
        System.setProperty("proxyHost", "127.0.0.1");
        System.setProperty("proxyPort", "17890");
        //发送后，返回messageID
        String response = FirebaseMessaging.getInstance(firebaseApp).send(message);
        log.info("单个设备推送成功 : "+response);
    }


       /**
        * @description 多设备推送
        * @param tokens 设备token
        * @param title 标题
        * @param body  内容
        * @date     2024/1/17
        * @author   cloud fly
        * 借助 REST API 与 Admin FCM API，您可以指定一系列设备注册令牌，并将消息多播到这些设备。每次调用时，您最多可以指定 500 个设备注册令牌。
        */
    public static void pushMulti(List<String> tokens, String title, String body) throws  FirebaseMessagingException {
        for (int i = 0; i < tokens.size(); i += 500) {
            List<String> tokenSub = tokens.subList(i, Math.min(i + 500, tokens.size()));
            System.setProperty("proxyHost", "127.0.0.1");
            System.setProperty("proxyPort", "17890");
            MulticastMessage message = MulticastMessage.builder()
                .putData("title", title)
                .putData("body", body)
                .addAllTokens(tokenSub)
                .build();
            BatchResponse response = FirebaseMessaging.getInstance().sendMulticast(message);
            if (response.getFailureCount() > 0) {
                List<SendResponse> responses = response.getResponses();
                List<String> failedTokens = new ArrayList<>();
                for (int j = 0; j < responses.size(); j++) {
                    if (!responses.get(j).isSuccessful()) {
                        // The order of responses corresponds to the order of the registration tokens.
                        failedTokens.add(tokenSub.get(j));
                    }
                }
                log.info("List of tokens that caused failures: {}" , failedTokens);
            }
        }

    }


//    public static void main(String[] args) throws FirebaseMessagingException, IOException {
//        String token = "eFjve8A1Q-mr52_H36kKiw:APA91bHeFT3ubLXlmmtf9VHs-SiFEvX1-zAHcQIZ8FqnDj0PS0IbVjtz46lHMC5qLCTB281tQkGtycDktIQ6HAqj26hphPeUm3PjH7J0LrNpAPb_FziQmeIVt2P1faYYTL4pmhGlaMQP";
//        FireBaseUtil.pushSingle(token,"Test","123456");
//
//
//    }


}